﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Components_Home : System.Web.UI.UserControl
{
    DatabaseHelper helper;
    protected void Page_Load(object sender, EventArgs e)
    {
        int iProvinceID = Convert.ToInt32(Session["ProvinceID"]);
        if (Page.RouteData.Values["FunctionName"] != null)//vua load vao
        {
            string FunctionName = Server.HtmlEncode(Page.RouteData.Values["FunctionName"].ToString().ToLower());
            if (FunctionName == "san-pham-moi")
            {
                loadProduct("N", 1000, "chi-tiet-san-pham", iProvinceID);
                div_New.Style["Display"] = "Block";
                div_Liked.Style["Display"] = "None";
                div_New_All.Style["Display"] = "None";
                div_Liked_All.Style["Display"] = "None"; 
            }
            else if (FunctionName == "san-pham-ua-chuong")
            {
                loadProduct("L", 1000, "chi-tiet-san-pham", iProvinceID);
                div_New.Style["Display"] = "None";
                div_Liked.Style["Display"] = "Block";
                div_New_All.Style["Display"] = "None";
                div_Liked_All.Style["Display"] = "None"; 
            }
            else//load san pham moi va san pham ua chuong
            {
                loadProduct("N", 4, "chi-tiet-san-pham", iProvinceID);
                loadProduct("L", 4, "chi-tiet-san-pham", iProvinceID);
            }
        }
        else{
            //load san pham moi va san pham ua chuong
            loadProduct("N", 4, "chi-tiet-san-pham", iProvinceID);
            loadProduct("L", 4, "chi-tiet-san-pham", iProvinceID);
        }
    }
    
    private void loadProduct(string iIsNew = "N", int iPageSize = 4, string strFunctionName = "chi-tiet-san-pham", int iProvinceID = 0)
    {
        helper = new DatabaseHelper();
        System.Data.Common.DbParameter paramType = helper.Parameter;
        paramType.ParameterName = "IsNew";
        paramType.DbType = DbType.String;
        paramType.Value = iIsNew;
        helper.AddParameter(paramType);

        System.Data.Common.DbParameter paramProvinceID = helper.Parameter;
        paramProvinceID.ParameterName = "ProvinceID";
        paramProvinceID.DbType = DbType.Int32;
        paramProvinceID.Value = iProvinceID;
        helper.AddParameter(paramProvinceID);

        System.Data.Common.DbParameter paramPageSize = helper.Parameter;
        paramPageSize.ParameterName = "PageSize";
        paramPageSize.DbType = DbType.Int32;
        paramPageSize.Value = iPageSize;
        helper.AddParameter(paramPageSize);

        System.Data.Common.DbParameter paramFunctionName = helper.Parameter;
        paramFunctionName.ParameterName = "FunctionName";
        paramFunctionName.DbType = DbType.String;
        paramFunctionName.Value = strFunctionName;
        helper.AddParameter(paramFunctionName);

        DataTable dt = helper.ExecuteDataTable("Web_GetProduct", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
        if (iIsNew == "N")//San pham moi
        {
            lvProductNew.DataSource = dt;
            lvProductNew.DataBind();
            if (dt.Rows.Count == 0)
            {
                div_New.Style["Display"] = "None";
                div_New_All.Style["Display"] = "None";
            }
            else
            {
                if(Convert.ToInt32(dt.Rows[0]["TotalRows"]) <= 4)
                    div_New_All.Style["Display"] = "None";
            }
        }
        if (iIsNew == "L")//San pham ua chuong
        {
            lvLiked.DataSource = dt;
            lvLiked.DataBind();
            if (dt.Rows.Count == 0)
            {
                div_Liked.Style["Display"] = "None";
                div_Liked_All.Style["Display"] = "None";
            }
            else
            {
                if (Convert.ToInt32(dt.Rows[0]["TotalRows"]) <= 4)
                    div_Liked_All.Style["Display"] = "None";
            }
        }
    }
    protected void btnOrder_Command(object sender, CommandEventArgs e)
    {
        try
        {
            //San pham moi
            if (e.CommandArgument != null)
            {
                /*TODO*/
                string str = e.CommandArgument.ToString();
                string[] arrListProduct = str.Split('@');
                int iProductID = Convert.ToInt32(arrListProduct[0]);
                string strProductName   = arrListProduct[1];
                string strProductCode   = arrListProduct[2];
                string strImagePath     = arrListProduct[3];
                double dPrice = Convert.ToDouble(arrListProduct[4]);
                string strIsPromotion = arrListProduct[5];
                int iWeight = 1;

                createCartTable(iProductID, strProductName, strProductCode, strImagePath, dPrice, iWeight, Convert.ToInt32(strIsPromotion));
                Response.Redirect(Request.UrlReferrer.AbsolutePath, false);
            }
            else
            {
                /*TODO*/
                ControlUtil.LogError("Error Add To Cart Page Home-btnOrder_Command");
            }
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("Error Add To Cart Page Home-btnOrder_Command:" + ex.Message);
        }
    }
    protected void btnOrderLiked_Command(object sender, CommandEventArgs e)
    {
        //San pham ua chuong
        try
        {
            if (e.CommandArgument != null)
            {
                /*TODO*/
                string str = e.CommandArgument.ToString();
                string[] arrListProduct = str.Split('@');
                int iProductID = Convert.ToInt32(arrListProduct[0]);
                string strProductName = arrListProduct[1];
                string strProductCode = arrListProduct[2];
                string strImagePath = arrListProduct[3];
                double dPrice = Convert.ToDouble(arrListProduct[4]);
                int iWeight = 1;
                string strIsPromotion = arrListProduct[5];
                createCartTable(iProductID, strProductName, strProductCode, strImagePath, dPrice, iWeight, Convert.ToInt32(strIsPromotion));
                Response.Redirect(Request.UrlReferrer.AbsolutePath, false);
            }
            else
            {
                /*TODO*/
                ControlUtil.LogError("Error Add To Cart Page Home-btnOrderLiked_Command");
            }

        }
        catch (Exception ex)
        {
            ControlUtil.LogError("Error Add To Cart Page Home-btnOrderLiked_Command:" + ex.Message);
        }
    }
    #region Custom Method
    private void createCartTable(int iProductID, string strProductName, string strProductCode, string strImagePath, double dPrice, int iWeight, int IsPromomtion = 1)
    {
        try
        {
            DataTable dt;
            if (Session["ShoppingCart"] == null)//chua ton tai san pham trong Shopping Cart
            {
                dt = new DataTable();
                dt.Columns.Add("ProductID", System.Type.GetType("System.Int32"));
                dt.Columns.Add("IsPromotion", System.Type.GetType("System.Int32"));
                dt.Columns.Add("ProductName", System.Type.GetType("System.String"));
                dt.Columns.Add("ProductCode", System.Type.GetType("System.String"));
                dt.Columns.Add("ImagePath", System.Type.GetType("System.String"));
                dt.Columns.Add("Price", System.Type.GetType("System.Double"));
                dt.Columns.Add("Weight", System.Type.GetType("System.Int32"));
                dt.Columns.Add("Amount", System.Type.GetType("System.Double"));

                DataRow drNew = dt.NewRow();
                drNew["ProductID"]      = iProductID;
                drNew["IsPromotion"]    = IsPromomtion;
                drNew["ProductName"]    = strProductName.Trim();
                drNew["ProductCode"]    = strProductCode.Trim();
                drNew["ImagePath"]      = strImagePath.Trim();
                drNew["Price"]          = dPrice;
                drNew["Weight"]         = iWeight;
                drNew["Amount"]          = iWeight * dPrice;
                dt.Rows.Add(drNew);
            }
            else//Da co san pham trong ShoppingCart
            {
                dt = (DataTable)Session["ShoppingCart"];
                if (dt.Select("ProductID=" + iProductID).Count() > 0)//Chi thay doi Shopping Cart cua san pham da ton tai
                {
                    DataRow[] rowArr = dt.Select("ProductID=" + iProductID);
                    if (rowArr.Count() > 0)
                    {
                        DataRow row = rowArr[0];
                        row["Weight"] = Convert.ToInt32(row["Weight"].ToString().Replace(",", "")) + iWeight;//tang trong luong len 1
                        row["Amount"] = Convert.ToDouble(row["Amount"]) + (Convert.ToDouble(row["Price"]) * iWeight);// tinh lai thanh tien
                    }
                }
                else
                {
                    DataRow drNew = dt.NewRow();
                    drNew["ProductID"] = iProductID;
                    drNew["IsPromotion"] = IsPromomtion;
                    drNew["ProductName"] = strProductName.Trim();
                    drNew["ProductCode"] = strProductCode.Trim();
                    drNew["ImagePath"] = strImagePath.Trim();
                    drNew["Price"] = dPrice;
                    drNew["Weight"] = iWeight;
                    drNew["Amount"] = iWeight * dPrice;
                    dt.Rows.Add(drNew);
                }

            }
            Session["ShoppingCart"] = dt;
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("CreateTable Shopping Cart Page Home:" + ex.Message.ToString());
        }
        //return dt;
    }
    #endregion End Custom Method
}